package cn.ztydata.teachingsystem.heaven.dao;

import cn.ztydata.teachingsystem.common.Page;
import cn.ztydata.teachingsystem.heaven.common.WebContext;
import cn.ztydata.teachingsystem.heaven.cons.QuestionCons;
import cn.ztydata.teachingsystem.heaven.cons.Roles;
import cn.ztydata.teachingsystem.heaven.entity.Answer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 问题答案Dao类
 *
 * @author lyj
 * @since 2015-3-20
 */
@Repository
public class AnswerDao extends BaseDao {
    @Autowired
    private WebContext webContext;

    /**
     * 新增问题答案
     *
     * @param answer 答案实体
     * @return int 受影响行数
     * @author lyj
     * @since 2015-3-20
     */
    public int addAnswer(Answer answer){
        StringBuilder sql = new StringBuilder("INSERT INTO t_answer VALUES (NULL, :sContent, :tiBest, :iQuestionId, :iCreatorId, :tiRole, NOW())");

        MapSqlParameterSource param = new MapSqlParameterSource();
        param.addValue("sContent", answer.getContent());
        param.addValue("tiBest", QuestionCons.NOT_BEST); //答案状态默认不是最佳
        param.addValue("iQuestionId", answer.getQuestionId());
        param.addValue("iCreatorId", webContext.getUserId());
        param.addValue("tiRole", webContext.getRole() == Roles.STUDENT ? 1 : 0); //角色

        log.debug("新增问题答案");
        return namedParameterJdbcTemplate.update(sql.toString(), param);
    }

    /**
     * 设置最佳答案
     *
     * @param answer 答案实体
     * @return int
     * @author lyj
     * @since 2015-3-20
     */
    public int setBest(Answer answer){
        StringBuilder sql = new StringBuilder("UPDATE t_answer SET tiBest = :tiBest WHERE id = :id");

        MapSqlParameterSource param = new MapSqlParameterSource();
        param.addValue("tiBest", answer.getBest());
        param.addValue("id", answer.getId());

        log.debug("设置最佳答案");
        return namedParameterJdbcTemplate.update(sql.toString(), param);
    }

    /**
     * 根据ID统计答案
     *
     * @param id 答案ＩＤ
     * @return int
     * @author lyj
     * @since 2015-3-20
     */
    public int getById(final long id, final long creatorId, final long role){
        StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM t_answer WHERE id = :id ");

        MapSqlParameterSource param = new MapSqlParameterSource();
        param.addValue("id", id);

        if (creatorId > 0) {
            sql.append(" AND iCreatorId = :creatorId AND tiRole = :role");
            param.addValue("creatorId", creatorId);
            param.addValue("role", role == Roles.STUDENT ? 1 : 0);
        }

        return namedParameterJdbcTemplate.queryForObject(sql.toString(), param, Integer.class);
    }


    /**
     * 删除答案(只能删除不是最佳的答案)
     *
     * @param id 答案ID
     * @return int
     * @author lyj
     * @since 2015-3-20
     */
    public int deleteAnswer(final long id){
        StringBuilder sql = new StringBuilder("DELETE FROM t_answer WHERE id = :id AND tiBest = 0");
        log.debug("删除答案");
        return namedParameterJdbcTemplate.update(sql.toString(), new MapSqlParameterSource().addValue("id", id));
    }

    /**
     * 根据问题ID删除答案
     *
     * @param questionId 问题ID
     * @return void
     * @author lyj
     * @since 2015-3-20
     */
    public int deleteAnswerByQueId(final long questionId){
        StringBuilder sql = new StringBuilder("DELETE FROM t_answer WHERE iQuestionId = :iQuestionId");
        log.debug("根据问题ID删除答案");
        return namedParameterJdbcTemplate.update(sql.toString(), new MapSqlParameterSource().addValue("iQuestionId", questionId));
    }

    /**
     * 获取回答列表
     *
     * @param questionId 问题ID
     * @param pageNum 当前页码
     * @param pageSize 每页条数
     * @return page
     * @author lyj
     * @since 2015-3-20
     */
    public Page<Answer> getList(final long questionId, final int pageNum, final int pageSize){
        StringBuilder sql = new StringBuilder("SELECT id, sContent, tiBest, iCreatorId, tiRole, dtCreate FROM t_answer WHERE iQuestionId = :iQuestionId");
        StringBuilder sqlCount = new StringBuilder("SELECT COUNT(*) FROM t_answer WHERE iQuestionId = :iQuestionId");

        MapSqlParameterSource param = new MapSqlParameterSource().addValue("iQuestionId", questionId);

        //获取总条数
        int total = namedParameterJdbcTemplate.queryForObject(sqlCount.toString(), param, Integer.class);

        if (total == 0) {
            log.debug("total == 0");
            return new Page<>();
        }

        //追加排序
        sql.append(" ORDER BY tiBest DESC");

        //追加limit限制
        sql.append(getLimitStr(pageNum, pageSize));

        List<Answer> answerList = namedParameterJdbcTemplate.query(sql.toString(), param, new RowMapper<Answer>() {
            @Override
            public Answer mapRow(ResultSet rs, int rowNum) throws SQLException {
                Answer answer = new Answer();

                answer.setId(rs.getLong("id"));
                answer.setContent(rs.getString("sContent"));
                answer.setBest(rs.getInt("tiBest"));
                answer.setCreatorId(rs.getLong("iCreatorId"));
                answer.setRole(rs.getInt("tiRole"));
                answer.setCreate(rs.getTimestamp("dtCreate"));

                return answer;
            }
        });

        log.debug("获取回答列表");
        return new Page<>(total, pageSize, pageNum,answerList);
    }


}
